import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_riverpod_test/app_router.dart';
import 'package:flutter_riverpod_test/manager/app_manager.dart';
import 'package:flutter_riverpod_test/model/cart_item.dart';
import 'package:flutter_riverpod_test/model/product.dart';
import 'package:flutter_riverpod_test/view/cart/cart_info_list_item.dart';

import '../../model/cart.dart';

class CartInfoPage extends StatelessWidget {
  const CartInfoPage({super.key});

  /// 处理数量变事件
  handleCountChange(Product product, Cart cart, CartItem? cartItem, int change) {
    if (change == 0) {
      return;
    }
    if (cartItem == null && change < 0) {
      return;
    }
    int curCount = cartItem?.count ?? 0;
    if (curCount == 0 && change < 0) {
      return;
    }
    if (product.saleCount >= product.totalCount && change > 0) {
      return;
    }
    if (cartItem != null && change < 0 && cartItem!.count + change < 0) {
      return;
    }

    if (change > 0) {
      if (cartItem == null) {
        CartItem newItem = CartItem(product: product);
        newItem.count = change;
        cart.addItem(newItem);
      } else {
        cartItem!.count += change;
      }
    } else {
      if (cartItem!.count == 0) {
        cart.removeItem(cartItem);
      } else {
        cartItem!.count += change;
      }
    }
    product.saleCount += change;

    cart.updateItems(cart.items);
    AppManager.shared.refreshProduct(AppManager.shared.storeProducts);
    AppManager.shared.refreshCart(AppManager.shared.carts);
  }

  @override
  Widget build(BuildContext context) {
    Cart cart = AppNavigator.lastArguments as Cart;
    final provider = ChangeNotifierProvider((_) => cart);
    return Scaffold(
      appBar: AppBar(
        title: Text("购物车：${cart.id}"),
      ),
      backgroundColor: Colors.white,
      body: Consumer(builder: (context, ref, child) {
        var products = ref.watch(AppManager.shared.provider.select((value) => value.storeProducts));
        Cart cart = ref.watch(provider);

        return ListView.builder(
          itemCount: products.length,
          itemExtent: CartInfoListItem.rowHeight,
          itemBuilder: (context, index) {
            Product product = products[index];
            CartItem? cartItem;
            for(final item in cart.items) {
              if (item.product.id == product.id) {
                cartItem = item;
                break;
              }
            }
            return CartInfoListItem(
              product: product,
              cartItem: cartItem,
              callback: (product, cartItem, change) => handleCountChange(product, cart, cartItem, change)
            );
          },
        );
      }),
    );
  }
}
